package net.lzzy.practices.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstant;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.Course;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.repositonies.CourseRepository;
import net.lzzy.practices.repositonies.UserRepository;
import net.lzzy.practices.services.CourseService;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.StringUtil;
import net.lzzy.practices.web.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author m
 */
@RestController

@CrossOrigin
@RequestMapping(ApiConstant.ROUTE_COURSE_ROOT)
@Api("课程管理")
public class CourseApiController {
    private  final CourseService courseService;

    private final UserService userService;
    @Autowired
    public CourseApiController(CourseRepository service, CourseRepository courseRepository, UserRepository userRepository, CourseService courseService, UserService userService) {
        this.courseService = courseService;
        this.userService = userService;

    }
    @ApiOperation("查询所有课程")
    @ApiImplicitParam(name = "token",value = "操作人令牌",dataType = "String",dataTypeClass = String.class,paramType = "query",required = true)
    @GetMapping(ApiConstant.ROUTE_COURSE_ALL)
    public ApiResult getCourses(@RequestParam String token){
        List<VmCourse> courses= new ArrayList<>();
        courseService.get().forEach(course -> courses.add(VmCourse.create(course,false)));
        return  new ApiResult(true,courses.size()+"",courses);

//        return null;
    }
    @ApiOperation("查询开放，关闭课程")
    @GetMapping(ApiConstant.ROUTE_COURSE_OPEN)
    public ApiResult getOpenCourses(@RequestParam String token){
        List<VmCourse> courses= new ArrayList<>();
        courseService.get(true).forEach(course -> courses.add(VmCourse.create(course,false)));
        return  new ApiResult(true,courses.size()+"",courses);

    }

    @GetMapping(ApiConstant.ROUTE_COURSE_PAGE)
    public  ApiResult getPageCourses(@RequestParam String token,@RequestParam int page,@RequestParam int size){
        List<VmCourse> courses = new ArrayList<>();
        courseService.get(page,size).forEach(course -> courses.add(VmCourse.create(course,false)));
        return  new ApiResult(true,courses.size()+"",courses);

    }

    @GetMapping(ApiConstant.ROUTE_COURSE_OPEN_PAGE)
    public  ApiResult getPageOpenCourses(@RequestParam String token,@RequestParam int page,@RequestParam int size){
        List<VmCourse> courses = new ArrayList<>();
        courseService.get(page,size,true).forEach(course -> courses.add(VmCourse.create(course,false)));
        return  new ApiResult(true,courses.size()+"",courses);
    }

    @GetMapping(ApiConstant.ROUTE_COURSE_STUDENT)
    public  ApiResult getStudentCourses(@RequestParam String token, @RequestParam(name = "id")UUID studentId){
        List<VmCourse> courses = new ArrayList<>();
        courseService.getStudentsCourses(studentId).forEach(course -> courses.add(VmCourse.create(course, false)));
        return  new ApiResult(true,courses.size()+"",courses);
    }
    @GetMapping(ApiConstant.ROUTE_COURSE_TEACHER)
    public  ApiResult getTeacherCourses(@RequestParam String token, @RequestParam(name = "id")UUID teacherId){
        List<VmCourse> courses = new ArrayList<>();
        courseService.getTeachersCourses(teacherId).forEach(course -> courses.add(VmCourse.create(course,false)));
        return  new ApiResult(true,courses.size()+"",courses);
    }

    /**
     * 新增/更新
     * @param id 当id为null 增加，否则为更新
     * @param info
     * @return
     */
    private ApiResult addOrUpdate(UUID id,CourseInfo info){
        String token = info.getToken();
        String name = info.getName();
        String desc = info.getDesc();
        String cover= info.getCover();
        String teacherId=info.getTid();
        boolean open = info.isOpen();
        if(StringUtil.isEmpty(name)||
            StringUtil.isEmpty(desc)||
            StringUtil.isEmpty(cover)||
            StringUtil.isEmpty(teacherId)
        ){
            return  new ApiResult(false, Messages.MISS_ARGS.toString(), null);
        }
        User teacher = userService.getById(UUID.fromString(teacherId));
        if(teacher== null ){
            return new ApiResult(false,Messages.WRONG_ID.toString(), null);
        }
        Course course;
        boolean add=id ==null;
        if(add){
            course= new Course();
            course.setTeacher(teacher);
        }else {
            course= courseService.getById(id);
            if(course== null ){
                return new ApiResult(false,Messages.WRONG_ID.toString(), null);
            }
        }
        course.setUpdateTime(new Date());
        course.setOpen(open);
        course.setName((name));
        course.setCover(cover);
        course.setDescription(desc);
        if(add){
            return  new ApiResult(true,Messages.SUCCESC.toString(), VmCourse.create(courseService.add(course),true));
        }else{
            Course updated= courseService.update(course,token);
            if(updated ==null){
                return new ApiResult(false,Messages.NO_PERISSION.toString(), null);
            }
         return  new ApiResult(true ,Messages.SUCCESC.toString(), VmCourse.create(updated,true));
        }

    }
    @PostMapping(ApiConstant.ROUTE_COURSE_ADD)
    public ApiResult add(@RequestBody CourseInfo info){
        return  addOrUpdate( null ,info);
    }
    @ApiOperation("编辑课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "课程",dataType = "UUID",dataTypeClass = UUID.class,paramType = "path",required = true),
            @ApiImplicitParam(name = "info",value = "课程信息",dataType = "CourseInfo",dataTypeClass = CourseInfo.class,paramType = "body",required = true)
    })
    @PostMapping(ApiConstant.ROUTE_COURSE_PUT)
    public  ApiResult update(@PathVariable UUID id,@RequestBody CourseInfo courseInfo){
        return  addOrUpdate(id,courseInfo);
    }
    @ApiOperation("开放，关闭课程")
    @PostMapping(ApiConstant.ROUTE_COURSE_OPEN_CLOSE)
    public ApiResult openClose(CourseOpenInfo info){
        String token= info.getToken();
        String strCourseId= info.getCid();
        boolean open = info.isOpen();
        if(StringUtil.isEmpty(token) || StringUtil.isEmpty(strCourseId)){
            return  new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        Course course = courseService.openCloseCoures(UUID.fromString(strCourseId),open,token);
        if(course==null){
            return  new ApiResult(false,Messages.NO_PERISSION.toString(), null);
        }
        return  new ApiResult(true,Messages.SUCCESC.toString(), VmCourse.create(course,true));
    }
    @DeleteMapping(ApiConstant.ROUTE_COURSE_REMOVE)
    public ApiResult delete(@RequestBody CourseKeyInfo info){
        String token = info.getToken();
        String strCourseId= info.getCid();
        if(StringUtil.isEmpty(token)||
            StringUtil.isEmpty(strCourseId)
        ){
        return new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        try {
            UUID courseId = UUID.fromString(strCourseId);
            Messages msg= courseService.remove(courseId,token);
            return  new ApiResult(msg==Messages.SUCCESC,msg.toString(),null);
        }catch (Exception e){
            return  new ApiResult(false,Messages.WRONG_ID.toString(), null);
        }

    }



}
